import axios from 'axios'
import { ElNotification } from 'element-plus'

import store from '../store'
import router from '@/router'
import { getToken } from '@/utils/auth'
import { baseUrl, apiUrl } from "@/utils/util"
import useUserStore from '@/store/modules/user'
// import https from 'https'

// 创建axios实例
// axios.defaults.withCredentials=true
const service = axios.create({
  baseURL: `${baseUrl}/${apiUrl}`, // api的base_url
  timeout: 10000,
  //这里关闭ssl验证，正式环境的时候要注释掉======
  // httpsAgent: new https.Agent({
  //   rejectUnauthorized: false
  // })
  //============================================
})

// request拦截器
service.interceptors.request.use(config => {
  let token = getToken()
  if (token) {
    config.headers['Authentication'] = token // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  Promise.reject(error)
}
)

// respone拦截器
service.interceptors.response.use(async (response) => {
  const res = response.data
  if (res.constructor === Blob) {
    return res;
  } else if (res.code != '0') {
    if (res.code == '1005' || res.code == '1001') { // Token过期了
    
      //const remeber = localStorage.getItem('remeber') //保持登录状态
      // try { 
      //   if (remeber == null) throw new Error('not remeber me')
      //    const data = await useUserStore().Login(JSON.parse(atob(remeber)))  
      //   localStorage.setItem('user', JSON.stringify(data)) 
      //   response.config.headers.Authentication = getToken()  
      //   const resData = (await axios(response.config))
      //   return resData.data
      // } catch (e) { console.log(e) }
 
      useUserStore().logOut().then(() => { 
        router.replace('/login')
      })
      return
    }
    ElNotification({ title: 'Prompt information', message: res.message? res.message:res.msg, type: 'warning', position: 'bottom-right' })
    return Promise.reject(res.message)
  }

  return response.data
}, error => {
  ElNotification({ title: 'Error Message', message: 'Service exception, please try again later！', type: 'error', duration: 5 * 1000, position: 'bottom-right' }) 
  return Promise.reject(error)
}
)

export default service




